package com.wn.cleandemo.utils.storage;

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.storage.StorageManager;

import com.wn.cleandemo.utils.ContextUtil;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 磁盘挂载判断反射工具
 */
//TODO 需要补充版本适配
public class StorageHolder {

    private StorageManager mStorageManager;
    private Method M_getVolumePaths;
    private Method M_getVolumeState;

    public StorageHolder() {
        Context context = ContextUtil.getContext();
        if (context != null && context.getApplicationContext() != null && Build.VERSION.SDK_INT >= 14) {
            mStorageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
            try {
                mStorageManager.getClass().getMethod("getVolumeList", new Class[0]);
                M_getVolumePaths = mStorageManager.getClass().getMethod("getVolumePaths", new Class[0]);
                M_getVolumeState = mStorageManager.getClass().getMethod("getVolumeState", String.class);
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    public List<String> GetAllMountedStorage() {
        if (Build.VERSION.SDK_INT < 14) {
            return getNormalExternal();
        }
        List<String> arrayList = new ArrayList<>();
        if (this.M_getVolumeState != null && this.mStorageManager != null) {
            String[] volumePaths = getVolumePaths();
            if (null != volumePaths && volumePaths.length > 0) {
                for (int i = 0; i < volumePaths.length; i++) {
                    try {
                        if (volumePaths[i] != null) {
                            if (this.M_getVolumeState.invoke(this.mStorageManager, volumePaths[i]).equals(Environment.MEDIA_MOUNTED)) {
                                arrayList.add(volumePaths[i]);
                            }
                        }
                    } catch (Exception e2) {
                        e2.printStackTrace();
                    }
                }
            }
        }

        return arrayList.isEmpty() ? getNormalExternal() : arrayList;
    }

    private List<String> getNormalExternal() {
        List<String> list1 = new ArrayList<>();
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            list1.add(Environment.getExternalStorageDirectory().getPath());
        }

        if (list1.isEmpty()) {
            return null;
        }
        return list1;
    }

    private String[] getVolumePaths() {
        Method method = this.M_getVolumePaths;
        Object obj = this.mStorageManager;
        if (method == null || obj == null) {
            return null;
        }
        try {
            return (String[]) method.invoke(obj, new Object[0]);
        } catch (Throwable e2) {
            e2.printStackTrace();
            return null;
        }
    }
}
